package com.zscat.mallplus.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.jfinal.kit.StrKit;
import com.zscat.mallplus.alipay.AliPayApi;
import com.zscat.mallplus.alipay.AliPayApiConfig;
import com.zscat.mallplus.alipay.AliPayBean;
import com.zscat.mallplus.core.enums.SignType;
import com.zscat.mallplus.core.kit.WxPayKit;
import com.zscat.mallplus.entity.WxPayBean;
import com.zscat.mallplus.enums.AllEnum;
import com.zscat.mallplus.enums.OrderStatus;
import com.zscat.mallplus.enums.StatusEnum;
import com.zscat.mallplus.exception.ApiMallPlusException;
import com.zscat.mallplus.fenxiao.entity.FenxiaoConfig;
import com.zscat.mallplus.fenxiao.entity.FenxiaoMemberTotal;
import com.zscat.mallplus.fenxiao.entity.FenxiaoRecords;
import com.zscat.mallplus.fenxiao.mapper.FenxiaoConfigMapper;
import com.zscat.mallplus.fenxiao.mapper.FenxiaoRecordsMapper;
import com.zscat.mallplus.jobhandler.MallplusJob;
import com.zscat.mallplus.oms.entity.*;
import com.zscat.mallplus.oms.mapper.*;

import com.zscat.mallplus.oms.vo.*;

import com.zscat.mallplus.pms.entity.PmsGifts;
import com.zscat.mallplus.pms.entity.PmsProduct;
import com.zscat.mallplus.pms.entity.PmsProductConsult;
import com.zscat.mallplus.pms.entity.PmsSkuStock;
import com.zscat.mallplus.pms.mapper.PmsGiftsMapper;
import com.zscat.mallplus.pms.mapper.PmsProductConsultMapper;
import com.zscat.mallplus.pms.mapper.PmsProductMapper;
import com.zscat.mallplus.pms.mapper.PmsSkuStockMapper;

import com.zscat.mallplus.pms.vo.ProductConsultParam;
import com.zscat.mallplus.sms.entity.*;
import com.zscat.mallplus.sms.mapper.*;
import com.zscat.mallplus.sms.vo.SmsCouponHistoryDetail;
import com.zscat.mallplus.sys.entity.SysSystemSetting;
import com.zscat.mallplus.sys.mapper.SysSystemSettingMapper;
import com.zscat.mallplus.ums.entity.*;
import com.zscat.mallplus.ums.mapper.SysAppletSetMapper;
import com.zscat.mallplus.ums.mapper.UmsIntegrationChangeHistoryMapper;
import com.zscat.mallplus.ums.mapper.UmsIntegrationConsumeSettingMapper;

import com.zscat.mallplus.ums.mapper.UmsMemberMapper;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.ValidatorUtils;
import com.zscat.mallplus.vo.ApplyRefundVo;

import com.zscat.mallplus.vo.Rediskey;

import com.zscat.mallplus.wxpay.WxPayApi;
import com.zscat.mallplus.wxpay.WxPayApiConfig;
import com.zscat.mallplus.wxpay.model.RefundModel;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author zscat
 * @since 2019-04-17
 */
@Service
public class OmsOrderServiceImpl extends ServiceImpl<OmsOrderMapper, OmsOrder> implements IOmsOrderService {
    private Logger log = LoggerFactory.getLogger(OmsOrderServiceImpl.class);

    @Resource
    private RedisUtil redisService;
    @Resource
    private PmsProductMapper productService;

    @Resource
    private UmsIntegrationConsumeSettingMapper integrationConsumeSettingMapper;
    @Resource
    private SmsFlashPromotionProductRelationMapper smsFlashPromotionProductRelationService;
    @Resource
    private PmsSkuStockMapper skuStockMapper;
    @Resource
    private SmsCouponHistoryMapper couponHistoryService;
    @Resource
    private IOmsOrderService orderService;

    @Resource
    private OmsOrderItemMapper orderItemService;
    @Resource
    private OmsOrderMapper orderMapper;

    @Resource
    private UmsMemberMapper memberService;
    @Resource
    private OmsOrderSettingMapper orderSettingMapper;

    @Resource
    private OmsOrderOperateHistoryMapper orderOperateHistoryService;
    @Resource
    private PmsGiftsMapper pmsGiftsService;

    @Resource
    private SysAppletSetMapper appletSetMapper;
    @Resource
    private OmsPaymentsMapper paymentsService;
    @Resource
    private SmsGroupMemberMapper groupMemberMapper;
    @Resource
    private OmsOrderReturnApplyMapper orderReturnApplyMapper;
    @Resource
    private PmsProductConsultMapper pmsProductConsultService;
    @Resource
    private SmsGroupRecordMapper groupRecordMapper;
    @Resource
    private SysSystemSettingMapper systemSettingMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void refund(OmsOrderReturnApply orderReturnApply) throws Exception {
        OmsOrder order = orderMapper.selectById(orderReturnApply.getOrderId());
        String refundStr = "";
        if (order != null ) {
            if (order.getPayType().equals(AllEnum.OrderPayType.weixinAppletPay.code())) { // 微信小程序支付
                if (StrKit.isBlank(order.getOrderSn())) {
                    throw new ApiMallPlusException("订单号为空");
                }

                OmsPayments payments = paymentsService.selectById(5);
                if (payments != null) {
                    //WxPayBean wxPayBean = JSONObject.parseObject(payments.getParamss(), WxPayBean.class);
                    SysSystemSetting setting = systemSettingMapper.selectById(1);
                    String refundNotifyUrl = setting.getSiteUrl().concat("/api/wxPay/refundNotify");

                    Map<String, String> params = RefundModel.builder()
                            .appid(payments.getAppId())
                            .mch_id(payments.getMchId())
                            .nonce_str(WxPayKit.generateStr())
                            .transaction_id(null)
                            .out_trade_no(order.getOrderSn())
                            .out_refund_no(WxPayKit.generateStr())
                            .total_fee(orderReturnApply.getProductRealPrice().toPlainString())
                            .refund_fee(orderReturnApply.getReturnAmount().toPlainString())
                            .notify_url(refundNotifyUrl)
                            .build()
                            .createSign(payments.getPartnerKey(), SignType.MD5);

                    refundStr = WxPayApi.orderRefund(false, params, payments.getCertPath(), payments.getMchId());
                } else {
                    throw new ApiMallPlusException("没有设置支付配置");
                }
                log.info("微信小程序退款返回=" + refundStr);
            } else if (order.getPayType().equals(AllEnum.OrderPayType.alipay.code())) { // 支付宝支付
                AlipayTradeRefundModel model = new AlipayTradeRefundModel();
                model.setOutTradeNo(order.getOrderSn());
                //  model.setTradeNo(order.getOrderSn());
                model.setRefundAmount(orderReturnApply.getReturnAmount().toPlainString());
                model.setRefundReason(orderReturnApply.getReason());
                OmsPayments payments = paymentsService.selectById(2);
                if (payments != null) {
                    AliPayApiConfig aliPayApiConfig = null;
                    AliPayBean aliPayBean = JSONObject.parseObject(payments.getParamss(), AliPayBean.class);
                    aliPayApiConfig = AliPayApiConfig.builder()
                            .setAppId(aliPayBean.getAppId())
                            .setAliPayPublicKey(aliPayBean.getPublicKey())
                            .setCharset("UTF-8")
                            .setPrivateKey(aliPayBean.getPrivateKey())
                            .setServiceUrl(aliPayBean.getServerUrl())
                            .setSignType("RSA2")
                            .build();

                    refundStr = AliPayApi.tradeRefundToResponse(model, aliPayApiConfig).getBody();;
                }

                log.info("支付宝退款返回=" + refundStr);
            } else if (order.getPayType().equals(AllEnum.OrderPayType.balancePay.code())) { // 余额支付
                UmsMember member = memberService.selectById(order.getMemberId());
                member.setBlance(member.getBlance().add(orderReturnApply.getReturnAmount()));
                memberService.updateById(member);
                orderReturnApply.setRefundStatus(1);
                orderReturnApplyMapper.updateById(orderReturnApply);
            }
//                order.setStatus(OrderStatus.REFUND.getValue());
//                order.setModifyTime(new Date());
//                orderMapper.updateById(order);
            if (order.getOrderType().equals(AllEnum.OrderType.PIN_GROUP.code())){
                SmsGroupMember groupMember = groupMemberMapper.selectOne(new QueryWrapper<SmsGroupMember>().eq("order_id",order.getId()));
                if (groupMember!=null){
                    groupMember.setStatus(1);
                    groupMemberMapper.updateById(groupMember);
                    SmsGroupRecord record = groupRecordMapper.selectById(groupMember.getGroupRecordId());
                    if (record!=null){
                        record.setStatus("1");
                        groupRecordMapper.updateById(record);
                    }
                }
            }
        }
    }

    private OmsOrderOperateHistory updateOrderInfo(Long id, OmsOrder oldOrder, OrderStatus newStatus) {
        String key = Rediskey.orderDetail + "orderid" + id;
        redisService.delete(key);
        oldOrder.setStatus(newStatus.getValue());
        oldOrder.setModifyTime(new Date());
        orderMapper.updateById(oldOrder);

        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(oldOrder.getId());
        history.setCreateTime(new Date());
        history.setOperateMan("shop");
        history.setPreStatus(oldOrder.getStatus());
        history.setOrderStatus(newStatus.getValue());
        return history;
    }


    @Override
    public CommonResult autoDeliveryOrder() {
        OmsOrderSetting orderSetting = orderSettingMapper.selectOne(new QueryWrapper<>());
        if (orderSetting != null) {
            List<OmsOrder> list = orderService.list(new QueryWrapper<OmsOrder>().eq("status", OrderStatus.DELIVERED.getValue()));
            for (OmsOrder order : list) {
                if (order.getPaymentTime().getTime()+ orderSetting.getConfirmOvertime() * 24*3600000 < System.currentTimeMillis()) {
                    log.info("Task确认收货,orderId="+order.getId());
                    order.setReceiveTime(new Date());
                    OmsOrderOperateHistory history = updateOrderInfo(order.getId(), order, OrderStatus.TO_COMMENT);
                    history.setNote("Task确认收货");
                    orderOperateHistoryService.insert(history);

                }
            }
        }
        return new CommonResult().success(null);
    }

    @Transactional
    @Override
    public CommonResult autoCommentOrder() {
        OmsOrderSetting orderSetting = orderSettingMapper.selectOne(new QueryWrapper<>());
        if (orderSetting != null) {
            List<OmsOrder> list = orderService.list(new QueryWrapper<OmsOrder>().eq("status", OrderStatus.TO_COMMENT.getValue()));
            for (OmsOrder order : list) {
                log.info("Task自动好评,orderId="+order.getId());
                if (order.getPaymentTime().getTime() + orderSetting.getCommentOvertime() * 24*3600000< (System.currentTimeMillis() )) {
                    OmsOrderOperateHistory history = updateOrderInfo(order.getId(), order, OrderStatus.TRADE_SUCCESS);
                    history.setNote("Task自动好评");
                    orderOperateHistoryService.insert(history);
                    OmsOrderItem queryO = new OmsOrderItem();
                    queryO.setOrderId(order.getId());
                    UmsMember member= memberService.selectById(order.getId());
                    List<OmsOrderItem> itemss = orderItemService.selectList(new QueryWrapper<>(queryO));
                    for (OmsOrderItem param : itemss) {
                        PmsProductConsult productConsult = new PmsProductConsult();

                        if (member != null) {
                            productConsult.setPic(member.getIcon());
                            productConsult.setMemberName(member.getNickname());
                            productConsult.setMemberId(member.getId());
                        }
                        PmsProduct product = productService.selectById(param.getProductId());
                        if(product!=null){
                            productConsult.setStoreId(product.getStoreId());
                            productConsult.setGoodsName(product.getName());
                        }
                        productConsult.setGoodsId(param.getProductId());
                        productConsult.setOrderId(order.getId());
                        String []co=new String []{"好买家，，合作愉快!!!","很好的买家，谢谢亲的惠顾，欢迎再次光临","祝亲合家欢乐","感谢您对小店的支持! 欢迎下次在来!","感谢您对我们的支持，您已成我们的会员享受本店特价优惠活动，随时欢迎您的光临!"};
                        Random ranInt = new Random();
                        productConsult.setConsultContent(co[ranInt.nextInt(4)]);
                        productConsult.setStars(3);
                        productConsult.setEmail(param.getProductPic());


                        productConsult.setConsultAddtime(new Date());
                        productConsult.setType(AllEnum.ConsultType.ORDER.code());
                        pmsProductConsultService.insert(productConsult);

                    }
                }
            }
        }
        return new CommonResult().success(null);
    }

    @Override
    public CommonResult autoSucessOrder() {
        OmsOrderSetting orderSetting = orderSettingMapper.selectOne(new QueryWrapper<>());
        if (orderSetting != null) {
            List<OmsOrder> list = orderService.list(new QueryWrapper<OmsOrder>().eq("status", OrderStatus.TO_COMMENT.getValue()));
            for (OmsOrder order : list) {
                log.info("Task自动完成交易,orderId="+order.getId());
                if (order.getPaymentTime().getTime()+ orderSetting.getFinishOvertime() *24*3600000 < (System.currentTimeMillis() )) {
                    OmsOrderOperateHistory history = updateOrderInfo(order.getId(), order, OrderStatus.TRADE_SUCCESS);
                    history.setNote("Task自动完成交易");
                    orderOperateHistoryService.insert(history);
                }
            }
        }
        return new CommonResult().success(null);
    }

    @Override
    public CommonResult cancelTimeOutOrder() {
        OmsOrderSetting orderSetting = orderSettingMapper.selectOne(new QueryWrapper<>());
        if (orderSetting != null) {
            //查询超时、未支付的订单及订单详情
            List<OmsOrderDetail> timeOutOrders = orderMapper.getTimeOutOrders(orderSetting.getNormalOrderOvertime());
            if (CollectionUtils.isEmpty(timeOutOrders)) {
                return new CommonResult().failed("暂无超时订单");
            }
            //修改订单状态为交易取消
            List<Long> ids = new ArrayList<>();
            for (OmsOrderDetail timeOutOrder : timeOutOrders) {
                ids.add(timeOutOrder.getId());
            }
            orderMapper.updateOrderStatus(ids, OrderStatus.CLOSED.getValue());
            for (OmsOrderDetail timeOutOrder : timeOutOrders) {
                //解除订单商品库存锁定
                // orderMapper.releaseSkuStockLock(timeOutOrder.getOrderItemList());
                releaseStock(timeOutOrder);
                //修改优惠券使用状态
                updateCouponStatus(timeOutOrder.getCouponId(), timeOutOrder.getMemberId(), 0);
                //返还使用积分
                if (timeOutOrder.getUseIntegration() != null) {
                    UmsMember member = memberService.selectById(timeOutOrder.getMemberId());
                    //    memberService.updateIntegration(timeOutOrder.getMemberId(), member.getIntegration() + timeOutOrder.getUseIntegration());
                }
            }
        }
        return new CommonResult().success(null);
    }



    /**
     * 计算总金额
     */
    private BigDecimal calcTotalAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal totalAmount = new BigDecimal("0");
        for (OmsOrderItem item : orderItemList) {
            totalAmount = totalAmount.add(item.getProductPrice().multiply(new BigDecimal(item.getProductQuantity())));
        }
        return totalAmount;
    }

    /**
     * 锁定下单商品的所有库存
     */
    public void lockStockByOrder(List<OmsOrderItem> cartPromotionItemList, String type) {
        log.info("lockStockByOrder");
        for (OmsOrderItem item : cartPromotionItemList) {
            if (item.getType().equals(AllEnum.OrderItemType.GOODS.code())) {
                if (type != null && "6".equals(type)) {
                    SmsFlashPromotionProductRelation relation = smsFlashPromotionProductRelationService.selectById(item.getGiftGrowth());
                    if ((relation.getFlashPromotionCount() - item.getProductQuantity()) < 0) {
                        throw new ApiMallPlusException("SmsFlashPromotionProductRelation is stock out. goodsId=" + item.getProductId() + ", relation=" + relation.getId());
                    }
                    relation.setFlashPromotionCount(relation.getFlashPromotionCount() - item.getProductQuantity());
                    smsFlashPromotionProductRelationService.updateById(relation);
                }
                PmsProduct goods = productService.selectById(item.getProductId());
                if (goods != null && goods.getId() != null) {
                    PmsProduct newGoods = new PmsProduct();
                    newGoods.setId(goods.getId());
                    redisService.delete(String.format(Rediskey.GOODSDETAIL, goods.getId() + ""));
                    if (!ValidatorUtils.empty(item.getProductSkuId()) && item.getProductSkuId() > 0) {
                        PmsSkuStock skuStock = skuStockMapper.selectById(item.getProductSkuId());
                        if ((skuStock.getStock() - item.getProductQuantity()) < 0) {
                            throw new ApiMallPlusException("goods is stock out. goodsId=" + item.getProductId() + ", skuId=" + item.getProductSkuId());
                        } else {
                            skuStock.setId(item.getProductSkuId());
                            skuStock.setStock(skuStock.getStock() - item.getProductQuantity());
                            skuStockMapper.updateById(skuStock);
                        }
                    } else {
                        if ((goods.getStock() - item.getProductQuantity()) < 0) {
                            throw new ApiMallPlusException("goods is stock out. goodsId=" + item.getProductId() + ", goodsId=" + item.getProductSkuId());
                        }
                    }
                    newGoods.setSale(goods.getSale() + item.getProductQuantity());
                    newGoods.setStock(goods.getStock() - item.getProductQuantity());
                    productService.updateById(newGoods);
                }
            } else {
                PmsGifts goods = pmsGiftsService.selectById(item.getProductId());
                if (goods != null && goods.getId() != null) {
                    PmsGifts newGoods = new PmsGifts();
                    newGoods.setId(goods.getId());
                    if ((goods.getStock() - item.getProductQuantity()) < 0) {
                        throw new ApiMallPlusException("赠礼商品 goods is stock out. goodsId=" + item.getProductId() + ", goodsId=" + item.getProductSkuId());
                    }
                    newGoods.setStock(goods.getStock() - item.getProductQuantity());
                    pmsGiftsService.updateById(newGoods);
                }

            }

        }
    }

    /**
     * 锁定下单商品的所有库存
     */
    public void lockStock(List<OmsCartItem> cartPromotionItemList) {
        log.info("lockStock");
        for (OmsCartItem item : cartPromotionItemList) {
            PmsProduct goods = productService.selectById(item.getProductId());
            if (goods != null && goods.getId() != null) {
                PmsProduct newGoods = new PmsProduct();
                newGoods.setId(goods.getId());
                if (true) {
                    redisService.delete(String.format(Rediskey.GOODSDETAIL, goods.getId() + ""));
                    if (!ValidatorUtils.empty(item.getProductSkuId()) && item.getProductSkuId() > 0) {
                        PmsSkuStock skuStock = skuStockMapper.selectById(item.getProductSkuId());
                        if ((skuStock.getStock() - item.getQuantity()) < 0) {
                            throw new ApiMallPlusException("goods is stock out. goodsId=" + item.getProductId() + ", skuId=" + item.getProductSkuId());
                        } else {
                            skuStock.setId(item.getProductSkuId());
                            skuStock.setStock(skuStock.getStock() - item.getQuantity());
                            skuStockMapper.updateById(skuStock);
                        }
                    } else {
                        if ((goods.getStock() - item.getQuantity()) < 0) {
                            throw new ApiMallPlusException("goods is stock out. goodsId=" + item.getProductId() + ", goodsId=" + item.getProductSkuId());
                        }
                    }
                }
                newGoods.setSale(goods.getSale() + item.getQuantity());
                newGoods.setStock(goods.getStock() - item.getQuantity());
                productService.updateById(newGoods);
            }
        }
    }

    /**
     * 解锁下单商品的所有库存
     */
    @Override
    public void releaseStock(OmsOrder order) {
        List<OmsOrderItem> orderItemList = orderItemService.selectList(new QueryWrapper<OmsOrderItem>().eq("order_id", order.getId()));
        log.info("releaseStock");
        for (OmsOrderItem item : orderItemList) {
            if (item.getType().equals(AllEnum.OrderItemType.GOODS.code())) {
                if ("6".equals(order.getOrderType())) {
                    SmsFlashPromotionProductRelation relation = smsFlashPromotionProductRelationService.selectById(item.getGiftGrowth().longValue());
                    relation.setFlashPromotionCount(relation.getFlashPromotionCount() + item.getProductQuantity());
                    smsFlashPromotionProductRelationService.updateById(relation);
                }
                PmsProduct goods = productService.selectById(item.getProductId());
                if (goods != null && goods.getId() != null) {
                    PmsProduct newGoods = new PmsProduct();
                    newGoods.setId(goods.getId());
                    if (true) {
                        redisService.delete(String.format(Rediskey.GOODSDETAIL, goods.getId() + ""));
                        if (!ValidatorUtils.empty(item.getProductSkuId()) && item.getProductSkuId() > 0) {
                            PmsSkuStock skuStock = skuStockMapper.selectById(item.getProductSkuId());
                            skuStock.setId(item.getProductSkuId());
                            skuStock.setStock(skuStock.getStock() + item.getProductQuantity());
                            skuStockMapper.updateById(skuStock);
                        }
                    }
                    goods.setSale(goods.getSale() - item.getProductQuantity());
                    newGoods.setStock(goods.getStock() + item.getProductQuantity());
                    productService.updateById(newGoods);
                }
            } else {
                PmsGifts goods = pmsGiftsService.selectById(item.getProductId());
                if (goods != null && goods.getId() != null) {
                    PmsGifts newGoods = new PmsGifts();
                    newGoods.setId(goods.getId());
                    if ((goods.getStock() + item.getProductQuantity()) < 0) {
                        throw new ApiMallPlusException("goods is stock out. goodsId=" + item.getProductId() + ", goodsId=" + item.getProductSkuId());
                    }
                    newGoods.setStock(goods.getStock() + item.getProductQuantity());
                    pmsGiftsService.updateById(newGoods);
                }
            }
        }
    }

    /**
     * 判断下单商品是否都有库存
     */
    private boolean hasStock(List<OmsCartItem> cartPromotionItemList) {

        return true;
    }

    /**
     * 计算购物车中商品的价格
     */
    private ConfirmOrderResult.CalcAmount calcCartAmount(List<OmsCartItem> cartPromotionItemList, BigDecimal transFee, BigDecimal payAmount) {
        ConfirmOrderResult.CalcAmount calcAmount = new ConfirmOrderResult.CalcAmount();
        calcAmount.setFreightAmount(transFee);


        BigDecimal totalAmount = new BigDecimal("0");
        BigDecimal promotionAmount = new BigDecimal("0");
       /* CartMarkingVo vo = new CartMarkingVo();
        vo.setCartList(cartPromotionItemList);
        SmsBasicMarking basicMarking = basicMarkingService.matchOrderBasicMarking(vo);
        log.info("basicMarking=" + com.alibaba.fastjson.JSONObject.toJSONString(basicMarking));
        if (basicMarking != null) {
            promotionAmount = basicMarking.getMinAmount();
        }
        if (promotionAmount == null) {
            promotionAmount = BigDecimal.ZERO;
        }*/
        for (OmsCartItem cartPromotionItem : cartPromotionItemList) {
            totalAmount = totalAmount.add(cartPromotionItem.getPrice().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
            //  promotionAmount = promotionAmount.add(cartPromotionItem.getReduceAmount().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
        }
        calcAmount.setTotalAmount(totalAmount);
        calcAmount.setPromotionAmount(promotionAmount);
        if (payAmount.compareTo(BigDecimal.ZERO) > 0) {
            calcAmount.setPayAmount(payAmount.subtract(promotionAmount).add(transFee));
        } else {
            calcAmount.setPayAmount(totalAmount.subtract(promotionAmount).add(transFee));
        }
        if (calcAmount.getPayAmount().compareTo(BigDecimal.ZERO) <= 0) {
            calcAmount.setPayAmount(new BigDecimal("0.01"));
        }
        return calcAmount;
    }



    /**
     * 将优惠券信息更改为指定状态
     *
     * @param couponId  优惠券id
     * @param memberId  会员id
     * @param useStatus 0->未使用；1->已使用
     */
    private void updateCouponStatus(Long couponId, Long memberId, Integer useStatus) {
        if (couponId == null) {
            return;
        }
        //查询第一张优惠券
        SmsCouponHistory queryC = new SmsCouponHistory();
        queryC.setCouponId(couponId);
        if (useStatus == 0) {
            queryC.setUseStatus(1);
        } else {
            queryC.setUseStatus(0);
        }
        List<SmsCouponHistory> couponHistoryList = couponHistoryService.selectList(new QueryWrapper<>(queryC));
        if (!CollectionUtils.isEmpty(couponHistoryList)) {
            SmsCouponHistory couponHistory = couponHistoryList.get(0);
            couponHistory.setUseTime(new Date());
            couponHistory.setUseStatus(useStatus);
            couponHistoryService.updateById(couponHistory);
        }
    }

    /**
     * 获取订单促销信息
     */
    private String getOrderPromotionInfo(List<OmsOrderItem> orderItemList) {
        StringBuilder sb = new StringBuilder();
        for (OmsOrderItem orderItem : orderItemList) {
            sb.append(orderItem.getPromotionName());
            sb.append(",");
        }
        String result = sb.toString();
        if (result.endsWith(",")) {
            result = result.substring(0, result.length() - 1);
        }
        return result;
    }

    /**
     * 计算订单应付金额
     */
    private BigDecimal calcPayAmount(OmsOrder order) {
        if (order.getPromotionAmount() == null) {
            order.setPromotionAmount(BigDecimal.ZERO);
        }
        if (order.getFreightAmount() == null) {
            order.setFreightAmount(BigDecimal.ZERO);
        }
        if (order.getCouponAmount() == null) {
            order.setCouponAmount(BigDecimal.ZERO);
        }
        if (order.getVipAmount() == null) {
            order.setVipAmount(BigDecimal.ZERO);
        }
        if (order.getIntegrationAmount() == null) {
            order.setIntegration(0);
        }
        //总金额+运费-促销优惠-优惠券优惠-积分抵扣
        BigDecimal payAmount = order.getTotalAmount()
                .add(order.getFreightAmount())
                .subtract(order.getPromotionAmount())
                .subtract(order.getCouponAmount())
                .subtract(order.getIntegrationAmount())
                .subtract(order.getVipAmount());
        return payAmount;
    }

    /**
     * 计算订单优惠券金额
     */
    private BigDecimal calcIntegrationAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal integrationAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getIntegrationAmount() != null) {
                integrationAmount = integrationAmount.add(orderItem.getIntegrationAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return integrationAmount;
    }

    /**
     * 计算订单优惠券金额
     */
    private BigDecimal calcCouponAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal couponAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getCouponAmount() != null) {
                couponAmount = couponAmount.add(orderItem.getCouponAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return couponAmount;
    }

    /**
     * 计算订单活动优惠
     */
    private BigDecimal calcPromotionAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal promotionAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getPromotionAmount() != null) {
                promotionAmount = promotionAmount.add(orderItem.getPromotionAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return promotionAmount;
    }

    /**
     * 获取可用积分抵扣金额
     *
     * @param useIntegration 使用的积分数量
     * @param totalAmount    订单总金额
     * @param currentMember  使用的用户
     * @param hasCoupon      是否已经使用优惠券
     */
    private BigDecimal getUseIntegrationAmount(Integer useIntegration, BigDecimal totalAmount, UmsMember currentMember, boolean hasCoupon) {
        BigDecimal zeroAmount = new BigDecimal(0);
        //判断用户是否有这么多积分
        if (useIntegration.compareTo(currentMember.getIntegration()) > 0) {
            return zeroAmount;
        }
        //根据积分使用规则判断使用可用
        //是否可用于优惠券共用
        UmsIntegrationConsumeSetting integrationConsumeSetting = integrationConsumeSettingMapper.selectById(1L);
        if (hasCoupon && integrationConsumeSetting.getCouponStatus().equals(0)) {
            //不可与优惠券共用
            return zeroAmount;
        }
        //是否达到最低使用积分门槛
        if (useIntegration.compareTo(integrationConsumeSetting.getUseUnit()) < 0) {
            return zeroAmount;
        }
        //是否超过订单抵用最高百分比
        BigDecimal integrationAmount = new BigDecimal(useIntegration).divide(new BigDecimal(integrationConsumeSetting.getUseUnit()), 2, RoundingMode.HALF_EVEN);
        BigDecimal maxPercent = new BigDecimal(integrationConsumeSetting.getMaxPercentPerOrder()).divide(new BigDecimal(100), 2, RoundingMode.HALF_EVEN);
        if (integrationAmount.compareTo(totalAmount.multiply(maxPercent)) > 0) {
            return zeroAmount;
        }
        return integrationAmount;
    }

    /**
     * 对优惠券优惠进行处理
     *
     * @param orderItemList       order_item列表
     * @param couponHistoryDetail 可用优惠券详情
     */
    private void handleCouponAmount(List<OmsOrderItem> orderItemList, SmsCouponHistoryDetail couponHistoryDetail) {
        SmsCoupon coupon = couponHistoryDetail.getCoupon();
        if (coupon.getUseType().equals(0)) {
            //全场通用
            calcPerCouponAmount(orderItemList, coupon);
        } else if (coupon.getUseType().equals(1)) {
            //指定分类
            List<OmsOrderItem> couponOrderItemList = getCouponOrderItemByRelation(couponHistoryDetail, orderItemList, 0);
            calcPerCouponAmount(couponOrderItemList, coupon);
        } else if (coupon.getUseType().equals(2)) {
            //指定商品
            List<OmsOrderItem> couponOrderItemList = getCouponOrderItemByRelation(couponHistoryDetail, orderItemList, 1);
            calcPerCouponAmount(couponOrderItemList, coupon);
        }
    }

    /**
     * 对每个下单商品进行优惠券金额分摊的计算
     *
     * @param orderItemList 可用优惠券的下单商品商品
     */
    private void calcPerCouponAmount(List<OmsOrderItem> orderItemList, SmsCoupon coupon) {
        BigDecimal totalAmount = calcTotalAmount(orderItemList);
        for (OmsOrderItem orderItem : orderItemList) {
            //(商品价格/可用商品总价)*优惠券面额
            BigDecimal couponAmount = orderItem.getProductPrice().divide(totalAmount, 3, RoundingMode.HALF_EVEN).multiply(coupon.getAmount());
            orderItem.setCouponAmount(couponAmount);
        }
    }

    /**
     * 获取与优惠券有关系的下单商品
     *
     * @param couponHistoryDetail 优惠券详情
     * @param orderItemList       下单商品
     * @param type                使用关系类型：0->相关分类；1->指定商品
     */
    private List<OmsOrderItem> getCouponOrderItemByRelation(SmsCouponHistoryDetail couponHistoryDetail, List<OmsOrderItem> orderItemList, int type) {
        List<OmsOrderItem> result = new ArrayList<>();
        if (type == 0) {
            List<Long> categoryIdList = new ArrayList<>();
            for (SmsCouponProductCategoryRelation productCategoryRelation : couponHistoryDetail.getCategoryRelationList()) {
                categoryIdList.add(productCategoryRelation.getProductCategoryId());
            }
            for (OmsOrderItem orderItem : orderItemList) {
                if (categoryIdList.contains(orderItem.getProductCategoryId())) {
                    result.add(orderItem);
                } else {
                    orderItem.setCouponAmount(new BigDecimal(0));
                }
            }
        } else if (type == 1) {
            List<Long> productIdList = new ArrayList<>();
            for (SmsCouponProductRelation productRelation : couponHistoryDetail.getProductRelationList()) {
                productIdList.add(productRelation.getProductId());
            }
            for (OmsOrderItem orderItem : orderItemList) {
                if (productIdList.contains(orderItem.getProductId())) {
                    result.add(orderItem);
                } else {
                    orderItem.setCouponAmount(new BigDecimal(0));
                }
            }
        }
        return result;
    }






}
